<?php
	session_start();
	header("Content-Type: text/html;charset=utf-8");
	if(isset($_POST['signinname'])){
		$newusername=$_POST['signinname'];
		$_SESSION['newsigninname']=$_POST['signinname'];
	}elseif(isset($_SESSION['newsigninname'])){
		$newusername=$_SESSION['newsigninname'];
	}else{
		echo "新名字未设置！";
		exit();
	}
	if(isset($_SESSION['qusername'])&&isset($_SESSION['qevent'])){//有原名字，有绑定事件
		$oldusername=$_SESSION['qusername'];
		if(!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$newusername)) {
			echo "<script>alert('名字应该是中文');history.back(-1);</script>";
			exit();
		}
		if(mb_strlen($newusername,'utf-8')<2||mb_strlen($newusername,'utf-8')>6){
			echo "<script>alert('名字长度应该是2~6，你当前长度是".mb_strlen($newusername,'utf-8')."');history.back(-1);</script>";
			exit();
		}
		//创建连接
		$conn = mysqli_connect("localhost", "root", "", "signin");
		mysqli_query($conn,"set names utf8");
		//检测连接
		if (!$conn){
			die("Connection failed:".mysqli_connect_error());
		}
		$thisevent=$_SESSION['qevent'];
		$sql1 = "SELECT * FROM persons WHERE event='$thisevent' AND username='start'";
		$result1 = mysqli_query($conn, $sql1);
		if(!$row = mysqli_fetch_assoc($result1)){
			mysqli_close($conn);
			echo "事件".$thisevent."不在签到的时间范围内，修改名字失败！";
			exit();
		}
		$oldusername = mysqli_real_escape_string($conn,$oldusername);
		$newusername = mysqli_real_escape_string($conn,$newusername);
		$sql1 = "SELECT * FROM persons WHERE username='$oldusername' AND event='$thisevent'";
		$result1 = mysqli_query($conn, $sql1);
		if($row = mysqli_fetch_assoc($result1)){//该原用户这次签到已完成
			$sql11 = "SELECT * FROM persons WHERE username='$newusername' AND event='$thisevent'";
			$result11 = mysqli_query($conn, $sql11);
			if($row11 = mysqli_fetch_assoc($result11)){//该新用户这次签到已完成
				//已经签到不做处理
			}else{
				$sql2="update persons set username='$newusername' where username='$oldusername' AND event='$thisevent'";
				$result = mysqli_query($conn,$sql2);//处理数据库
				$_SESSION['qusername']=$newusername;//更新名字
			}
			mysqli_close($conn);
			echo "<title>修改成功！</title>";
			echo "<center>";
			echo "<h1>".$_SESSION['qusername'].",您好，您提交的请求已经处理好了！在下一次刷新就可以看到效果了!</h1>";
			echo "</center>";
			exit();
		}else{
			echo "<center>用户不存在，请重新签到！</center>";
			session_destroy();
			exit();
		}
	}else{
		echo "<center>用户不存在，请重新签到！</center>";
		session_destroy();
		exit();
	}
?>